"""LLM模块统一入口"""

from typing import Dict, Any, Optional
import logging
from backend.llm.base import BaseLLMProvider, LLMProviderFactory

# 导入所有提供商实现以确保它们被注册
from backend.llm.openai_provider import OpenAIProvider
from backend.llm.ollama_provider import OllamaProvider
from backend.llm.vllm_provider import VLLMProvider

# 导入本地模型提供商（如果有）
# from backend.llm.local_provider import LocalProvider

logger = logging.getLogger('llm')


class LLMManager:
    """LLM管理器，负责创建和管理LLM提供商实例"""
    
    _instance = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(LLMManager, cls).__new__(cls)
            cls._instance._initialize()
        return cls._instance
    
    def _initialize(self):
        """初始化LLM管理器"""
        self.providers = {}
    
    def get_provider(self, provider_name: str, config: Optional[Dict[str, Any]] = None) -> BaseLLMProvider:
        """获取或创建LLM提供商实例
        
        Args:
            provider_name: 提供商名称
            config: 配置参数
        
        Returns:
            LLM提供商实例
        """
        if provider_name not in self.providers:
            try:
                # 如果没有提供配置，使用空字典
                if config is None:
                    config = {}
                
                # 创建提供商实例
                provider = LLMProviderFactory.create_provider(provider_name, config)
                
                # 加载模型
                provider.load_model()
                
                # 存储提供商实例
                self.providers[provider_name] = provider
                
                logger.info(f"成功创建并初始化LLM提供商: {provider_name}")
            except Exception as e:
                logger.error(f"创建LLM提供商失败 {provider_name}: {str(e)}")
                raise
        
        return self.providers[provider_name]
    
    def get_available_providers(self) -> list:
        """获取所有可用的LLM提供商
        
        Returns:
            提供商名称列表
        """
        return LLMProviderFactory.get_available_providers()
    
    def close_all(self):
        """关闭所有LLM提供商资源"""
        for provider_name, provider in self.providers.items():
            try:
                provider.close()
                logger.info(f"成功关闭LLM提供商: {provider_name}")
            except Exception as e:
                logger.error(f"关闭LLM提供商失败 {provider_name}: {str(e)}")
        
        # 清空提供商字典
        self.providers.clear()


# 创建全局LLM管理器实例
llm_manager = LLMManager()

# 导出主要类和实例
__all__ = [
    'BaseLLMProvider',
    'LLMProviderFactory',
    'OpenAIProvider',
    'OllamaProvider',
    'VLLMProvider',
    'LLMManager',
    'llm_manager'
]